﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using RssReader.Core.BL;

namespace RssReader.Core.UI
{
	public class LoginControl : BaseControl
	{
		#region Private Properties
		private TextBox _tbEmail;
		private TextBox _tbPassword;
		private LinkButton _lbSubmit;
		#endregion

		#region Public Properties

		#endregion

		#region Constructors

		#endregion

		#region Private Methods
		protected override void AttachChildControls()
		{
			_tbEmail = this.FindControl("tbEmail") as TextBox;
			_tbPassword = this.FindControl("tbPassword") as TextBox;
			_lbSubmit = this.FindControl("lbSubmit") as LinkButton;

			if (_lbSubmit != null)
			{
				_lbSubmit.Click += new EventHandler(_lbSubmit_Click);
			}
		}

		protected void _lbSubmit_Click(object sender, EventArgs e)
		{
			CheckLogin();
		}

		private void CheckLogin()
		{
			string email = _tbEmail.Text;
			string password = _tbPassword.Text;
			bool isPass = false;
			if (Validation.Instance.IsEmpty(email))
			{
				this.ThrowError("email is empty");
			}
			else if (Validation.Instance.IsEmpty(password))
			{
				this.ThrowError("password is empty");
			}
			else if (!Validation.Instance.IsEmail(email))
			{
				this.ThrowError("wrong email format");
			}
			else
			{
				password = Global.Utility.EncryptString(password);
				User user = User.Load(email);
				if (user != null)
				{
					if (user.Password == password)
					{
						isPass = true;
					}
					else
					{
						this.ThrowError("wrong password");
					}
				}
				else
				{
					try
					{
						user = new User(email);
						user.Password = password;
						user.Save();
						isPass = true;
					}
					catch(Exception ex)
					{
						this.ThrowError(ex.Message);
					}
				}

				if (isPass)
				{
					this.CurrentPage.Session["Email"] = email;
					this.CurrentPage.Response.Redirect("RssList.aspx");
				}
			}
		}
		#endregion

		#region Public Methods

		#endregion
	}
}
